import 'package:family_expense/features/account_user/widgets/login_device_list.dart';
import 'package:family_expense/features/account_user/widgets/reset_login_password.dart';
import 'package:family_expense/features/authentication/widgets/account_unregister.dart';
import 'package:flutter/material.dart';
import 'package:my_flutter_core/my_flutter_core.dart';

class AccountGroupUserSecurity extends StatefulWidget {
  const AccountGroupUserSecurity({super.key});

  @override
  State<AccountGroupUserSecurity> createState() =>
      _AccountGroupUserSecurityState();
}

class _AccountGroupUserSecurityState extends State<AccountGroupUserSecurity> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('账号安全')),
      body: _buildBody(),
    );
  }

  /// Builds main body.
  Widget _buildBody() {
    return ListView(
      padding: const EdgeInsets.only(top: 10.0),
      children: [
        ListTile(
          title: const Text('修改密码'),
          trailing: const ListTileNavigateNextIcon(),
          onTap: () =>
              NavigatorHelper.push(context, const ResetLoginPassword()),
        ),
        ListTile(
          title: const Text('登录设备'),
          trailing: const ListTileNavigateNextIcon(),
          onTap: () => NavigatorHelper.push(context, const LoginDeviceList()),
        ),
        _buildEnableQuickLoginFuture(),
        const Divider(),
        ListTile(
          title: const Text('注销账号', style: TextStyle(color: Colors.red)),
          // contentPadding: EdgeInsets.symmetric(horizontal: 5.0),
          trailing: const ListTileNavigateNextIcon(),
          onTap: () => NavigatorHelper.push(context, const AccountUnregister()),
        ),
      ],
    );
  }

  // shared_preferences package is not compatible with FlutterFragmentActivity which is needed by local_auth package.
  // By now we only can disable the features rely on local_auth package.
  // /// Builds the [FutureBuilder] to get the current user and user collection.
  // /// Then checks on if current user is in the collection.
  // /// If so that means current user enabled quick login. Otherwise means not.
  Widget _buildEnableQuickLoginFuture() {
    final authStateService = AuthStateService.instance;

    return FutureBuilder<User?>(
      future: authStateService.currentUser,
      builder: (context, userSnapshot) {
        // Gets the retrieved user data.
        final user = userSnapshot.data;

        return FutureBuilder<Map<String?, User?>?>(
          future: authStateService.userCollection,
          builder: (context, userCollectionSnapshot) {
            // Gets the retrieved user collection data.
            final userCollection = userCollectionSnapshot.data;

            // Checks if current user is in the collection via the username.
            final currentUserInCollection =
                userCollection?.containsKey(authStateService.getMapKey(user)) ==
                true;

            return SwitchListTile(
              title: const Text('允许快速登录'),
              subtitle: const Text('退出登录后可通过指纹识别快速重新登录'),
              value: currentUserInCollection == true,
              onChanged: (checked) {
                if (checked) {
                  authStateService.saveUserToCollection(user!);
                  TokenService.saveTokenForUserInCollection(user);
                } else {
                  authStateService.removeFromUserInfoCollection(user!);
                  TokenService.removeTokenForUserInCollection(user);
                }

                // Just need to trigger the UI to build.
                if (mounted) {
                  setState(() {});
                }
              },
            );
          },
        );
      },
    );
  }
}
